// pages/videoSwiperPage/videoSwiperPage.js
import room3TestData from "../testData/testR3Data";
import room2TestData from "../testData/testR2Data";
import room1TestData from "../testData/testR1Data";
import room0TestData from "../testData/testR0Data";
var mfApi = require('../../api/api.js');

const app = getApp();
import bottomEnterTestData from "../testData/testBottomEnterData";

Page({

        /**
         * 页面的初始数据
         */
        data: {
                currentRoomIndex: app.globalData.gCurrentRoomIndex,
                baseUrl: app.globalData.baseUrl,

                /**
                 * 房间资源
                 */
                roomResourceData: null,
                localRoomData: null,
                roomUserData: null,

                scrollSelectId: "6",
                scrollSelectData: {},

                picIndex: 1,
                picCurrentIndex: 0,

                // 初次进入scroll滚动到的id
                initScrollToId: "",
                initId: "",

                videoShowUrl: '',
                videoPosterUrl: '',
                videoAgreeNum: 0,
                videoShareNum: 0,
                // 是否显示解锁r5 Tip
                isShowFirstTip: false,
                // 是否可以显示解锁r5的tip
                isAllowShowFirstTip: false,

                // 是否需要检查r5解锁状态
                isNeedCheckR5State: true,

                /**
                 * 底部入口数据
                 */
                bottomEnterData: bottomEnterTestData,

                /**
                 * 退出视频相关
                 */
                isShowExitVideo: false,
                exitVideoUrl: '',
                exitVideoPosterUrl: '',
                // 返回键
                top: 0,
                h: 0, //胶囊高度

                eventAfterFirstUnlockFrame: null,
        },

        onShareTimeline:function(){
 
        },
        /**
         * 生命周期函数--监听页面加载
         */
        onLoad: async function (options) {
                console.log(options)
                this.setData({
                        currentRoomIndex: app.globalData.gCurrentRoomIndex,
                        initId: options.selectId,
                        top: app.menu.top,
                        h: app.menu.height
                })
                let temp = this.getLocalData();
                this.setData({
                        localRoomData: temp,
                })
                this.showVideoContext = wx.createVideoContext('play-video');

                setTimeout(async () => {
                        await this.checkR5StateState(false);
                        await this.getRoomInfoApi();
                        await this.checkStampState();
                }, 1000);

        },

        async getRoomInfoApi(needSelect = true) {
                let tempData = await mfApi.http(mfApi.getRoomInfo(this.data.currentRoomIndex, app.globalData.openId), "GET", {});
                console.log(tempData);
                if (tempData.code != 200) {
                        wx.showToast({
                                icon: "none",
                                title: '后端服务异常',
                        })
                        return;
                };

                let videoData = tempData.result;
                videoData.forEach(element => {
                        let index = element.orderNo;
                        let tempLocal = this.data.localRoomData.posterData.find(sub => {
                                return sub.id == index;
                        })
                        element.isHori = tempLocal.isHori;
                });
                let tempid = this.data.initId
                this.setData({
                        roomResourceData: JSON.parse(JSON.stringify(videoData)),
                        initScrollToId: needSelect ? "thumb-item-" + tempid : ''
                })

                if (this.data.scrollSelectId) {
                        let temp = this.data.roomResourceData.find(e => {
                                return e.id == this.data.scrollSelectId
                        })

                        if (temp) {
                                this.setData({
                                        scrollSelectId: temp.id,
                                        scrollSelectData: temp,
                                });
                        }
                }

                if (!needSelect)
                        return;

                let tempIndex = this.data.roomResourceData.findIndex(e => {
                        return e.id == tempid
                })

                let temp = {
                        currentTarget: {
                                dataset: {

                                }
                        }
                };
                temp.currentTarget.dataset.index = tempIndex;
                temp.currentTarget.dataset.item = this.data.roomResourceData[tempIndex];
                this.onScrollItemClick(temp, needSelect);
        },

        async checkStampState() {
                let res = await mfApi.http(
                        mfApi.getRoomList(app.globalData.openId), "GET", {});
                if (res.code == 200) {
                        console.log("checkStampState   ===  ", res)
                        let roomInfo = res.result.roomList.find(e => {
                                return e.roomNo == this.data.currentRoomIndex;
                        })

                        this.setData({
                                roomUserData: roomInfo
                        })


                        let tempEnterData = this.data.bottomEnterData;
                        tempEnterData.forEach(element => {
                                // element.index
                                let roomInfo = res.result.roomList.find(e => {
                                        return e.roomNo == element.enterIndex;
                                });
                                if (roomInfo)
                                        element.unlockFlag = roomInfo.unlockFlag;
                        })

                        this.setData({
                                bottomEnterData: tempEnterData
                        })
                }
        },

        async checkR5StateState(isShowTip = false) {
                let res = await mfApi.http(
                        mfApi.getRoomList(app.globalData.openId), "GET", {});
                if (res.code != 200 || !res.result.roomList)
                        return;

                let r5Info = res.result.roomList.find(e => {
                        return e.roomNo == 5
                })

                // r5未解锁，一定要检查解锁状态
                if (r5Info.unlockFlag == "0") {
                        // setTimeout(() => {
                        //         this.setData({
                        //                 isShowFirstTip: r5Info.unlockFlag == "1"
                        //         })
                        // }, 5000);

                        this.setData({
                                isAllowShowFirstTip: true
                        })
                }

                // r5解锁后不再检查状态
                this.setData({
                        isNeedCheckR5State: r5Info.unlockFlag == "0"
                })
        },

        getLocalData() {
                let temp = {};
                if (this.data.currentRoomIndex >= 0) {
                        if (this.data.currentRoomIndex == 0) {
                                temp = room0TestData;
                        } else if (this.data.currentRoomIndex == 1) {
                                temp = room0TestData;
                        } else if (this.data.currentRoomIndex == 2) {
                                temp = room1TestData;
                        } else if (this.data.currentRoomIndex == 3) {
                                temp = room2TestData;
                        } else if (this.data.currentRoomIndex == 4)
                                temp = room3TestData;

                }
                return temp;
        },

        /**
         * 
         * @param {*} e 
         * @param {*} isInit 首次选择的视频  不处理弹窗
         */
        async onScrollItemClick(e, isInit) {
                let data = e.currentTarget.dataset.item;
                let index = e.currentTarget.dataset.index;
                console.log(data)
                console.log(index)

                // 先更新视频信息
                if (data.isHori) {
                        wx.redirectTo({
                                url: `/pages/videoSwiperHoriPage/videoSwiperHoriPage?selectId=${data.id}`,
                        })
                        return;
                }

                if (index == -1) {
                        this.setData({
                                scrollSelectId: this.data.roomResourceData[0].id,
                                scrollSelectData: this.data.roomResourceData[0],
                        });
                } else {
                        this.setData({
                                scrollSelectId: data.id,
                                scrollSelectData: data,
                        });
                }


                let tempData = await mfApi.http(mfApi.userCompleteVideo(app.globalData.openId, this.data.scrollSelectData.id), "POST", {});
                app.saveTrack(`R${this.data.currentRoomIndex}-video${data.orderNo}-播放`);

                await this.checkStampState();

                // 如果方向弹窗已出，返回
                if(this.data.isShowDirectTip)   
                        return;

                if(this.data.isAllowShowFirstTip && !isInit) {
                        this.showVideoContext.pause();
                        this.setData({
                                isShowFirstTip: true,
                                eventAfterFirstUnlockFrame: {
                                        action: "playVideo",
                                        data,
                                        index,
                                },
                                isAllowShowFirstTip: false
                        })
                        return;
                }

                // 后执行r5状态判断
                if (this.data.isNeedCheckR5State)
                        await this.checkR5StateState(true);

                // 所有数据操作结束后，执行播放或跳转
                if (data.isHori) {
                        wx.redirectTo({
                                url: `/pages/videoSwiperHoriPage/videoSwiperHoriPage?selectId=${data.id}`,
                        })
                        return;
                }

                this.showVideoContext.stop();
                this.showVideoContext.play();
        },

        // 点赞
        async onGoodClick() {
                let res = await mfApi.http(mfApi.userAgree(app.globalData.openId, this.data.scrollSelectData.id), "POST");
                app.saveTrack(`R${this.data.currentRoomIndex}-video${this.data.scrollSelectData.orderNo}-点赞`);
                this.getRoomInfoApi(false);
        },

        // 分享
        async onShareClick() {
                let res = await mfApi.http(mfApi.userShare(app.globalData.openId, this.data.scrollSelectData.id), "POST");
                app.saveTrack(`R${this.data.currentRoomIndex}-video${this.data.scrollSelectData.orderNo}-分享`);
                this.getRoomInfoApi(false);

                // let roomres = await mfApi.http(mfApi.getRoomList(app.globalData.openId), "GET", {});
                // if(roomres.code == 200 && roomres.result && roomres.result.shareVideoMarkFlag == 1) {
                //         // 提示已解锁r5
                // }

        },

        onShareAppMessage(object) {
                if(object.from == "menu") {
                        return {
                                title: 'LA MER邀你一同参展，探寻属于你的自愈空间',
                                path: `/pages/index/index?inChannel=commonShare`,
                                imageUrl: "https://morefun-active-1.oss-cn-shanghai.aliyuncs.com/2022_lamer_cream_show/share/wx-share.jpg",
                        }
                }

                this.onShareClick();
                app.saveTrack(`R${this.data.currentRoomIndex}-分享视频`);
                return {
                        title: 'LA MER邀你一同参展，探寻属于你的自愈空间',
                        path: `/pages/index/index?toPage=videoSwiper&selectRoom=${Number(this.data.currentRoomIndex)}&selectId=${this.data.scrollSelectId}&isHori=false`,
                        imageUrl: "https://morefun-active-1.oss-cn-shanghai.aliyuncs.com/2022_lamer_cream_show/share/wx-share.jpg",
                        // promise
                        success: () => {
                                console.log(" share ok")
                        },
                        fail: () => {
                                console.log(" share fail")
                        }
                }
        },

        onVideoEnded() {
                let tempIndex = this.data.roomResourceData.findIndex(e => {
                        return e.id == this.data.scrollSelectId
                })

                if (tempIndex < this.data.roomResourceData.length - 1) {
                        let temp = {
                                currentTarget: {
                                        dataset: {

                                        }
                                }
                        };
                        temp.currentTarget.dataset.index = tempIndex + 1;
                        temp.currentTarget.dataset.item = this.data.roomResourceData[tempIndex + 1];
                        this.onScrollItemClick(temp);
                }
        },

        preventTouchMove() {
                return
        },

        /**
         * 底部入口点击
         */
        onBottomEnterClick(e) {
                if(this.data.isAllowShowFirstTip) {
                        this.showVideoContext.pause();
                        this.setData({
                                isShowFirstTip: true,
                                eventAfterFirstUnlockFrame: null,
                                isAllowShowFirstTip: false
                        })
                        return;
                }

                console.log(e.detail)
                app.globalData.indexTurnDoor = e.detail;
                this.goBack();
        },
        onVideoUpdate(e) {
            if (e.detail.currentTime > 0.1) {
              this.setData({
                picCurrentIndex: 0
              })
            }
          },
        goBack() {
                this.showVideoContext.stop();
                var hour = new Date().getHours();
                let Back_Img_Type = 1;
                if (hour > 17 || hour < 6) {
                        Back_Img_Type = 3; //1是早上，2是中午，3是晚上
                } else if (hour > 5 && hour < 12) {
                        Back_Img_Type = 1;
                } else {
                        Back_Img_Type = 2;
                }

                this.setData({
                    picIndex:Back_Img_Type,
                    picCurrentIndex:this.data.currentRoomIndex
                });

                // 1-ROOM1.jpg
                let tempVideo = `${app.globalData.baseExitVideoUrl}/${Back_Img_Type}-ROOM${this.data.currentRoomIndex}.mp4`;
                let tempPoster = '';

                this.setData({
                        isShowExitVideo: true,
                        exitVideoUrl: tempVideo,
                        exitVideoPosterUrl: tempPoster
                })
        },

        /**
         * 退出视频结束
         */
        onExitVideoEnded() {
                wx.navigateBack({
                        delta: 2,
                })
        },

        onBackClick() {
                wx.navigateBack({
                        delta: 1,
                })
        },

        onFirstBottomBtnClick() {
                app.globalData.indexTurnDoor = 5;
                wx.navigateBack({
                  delta: 2,
                })
        },

                /**
         * 首次解锁提示框 关闭按钮
         */
        onFirstTipCloseClick() {
                this.setData({
                        isShowFirstTip: false
                })

                let tempEvent = this.data.eventAfterFirstUnlockFrame;
                if(!tempEvent) {
                        this.showVideoContext.play();
                        return;
                }

                if(tempEvent.action == "playVideo") {
                        let temp = {
                                currentTarget: {
                                        dataset: {
        
                                        }
                                }
                        };
                        temp.currentTarget.dataset.index = tempEvent.index;
                        temp.currentTarget.dataset.item = tempEvent.data;
                        this.onScrollItemClick(temp)
                }

                this.setData({
                        eventAfterFirstUnlockFrame: null
                })
        },
})